import smtplib
from typing import List
from email import utils
from email.header import Header
from email.mime.text import MIMEText


class Email:
    """邮件通告"""
    def __init__(self, **kwargs):
        self.server: str = ''
        self.port: int = 0
        self.is_ssl: bool = False
        self.sender: str = ''
        self.sender_description: str = ''  # 发送人显示名
        self.password: str = ''
        self.receiver: List[str] = []  # 接收人邮件清单 , 分隔; aa@qq.com,bb@cc.com

        if kwargs:
            self.init(**kwargs)

    def init(self, server, sender, password, receiver, sender_description='', port=25, is_ssl=False):
        self.server = server
        self.sender = sender
        self.sender_description = sender_description or sender
        self.password = password
        self.receiver = receiver
        self.port = port
        self.is_ssl = is_ssl

    def send(self, message, title='邮件发送'):
        # 消息
        message = MIMEText(message, 'plain', 'utf-8')
        message['From'] = utils.formataddr((self.sender_description, self.sender))
        message['TO'] = Header(','.join(self.receiver), 'utf-8')
        message['Message-id'] = utils.make_msgid()
        message['Date'] = utils.formatdate()
        message['Subject'] = Header(title)

        # 登陆系统开始发送
        if self.is_ssl:  # 加密协议
            smtp = smtplib.SMTP_SSL(self.server, self.port)
        else:
            smtp = smtplib.SMTP(self.server, self.port)
        smtp.login(self.sender, self.password)
        smtp.sendmail(self.sender, self.receiver, message.as_string())
        smtp.quit()


email = Email()


if __name__ == '__main__':
    email.init(server='smtp.qiye.aliyun.com', port=25, sender='shangtao.chen@miaoyun.io', sender_description='cs',
               password='_tofr6QF12ZZbpZ0I', receiver=['2757045143@qq.com'])
    email.send('测试1', '测试邮件\ntt\nhahah')
